package com.sun.apilimitrate.service;

import com.sun.apilimitrate.dto.RateConfig;
import org.redisson.api.RRateLimiter;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.ConcurrentHashMap;

@Service
public class DynamicRateLimitService {

    @Autowired
    private RedissonClient redissonClient;

    // 缓存限流器实例，避免重复创建
    private ConcurrentHashMap<String, RRateLimiter> limiterCache = new ConcurrentHashMap<>();

    /**
     * 动态获取限流器
     * @param key 限流key
     * @param rate 速率
     * @param rateInterval 时间间隔
     * @return 限流器实例
     */
    public RRateLimiter getDynamicRateLimiter(String key, long rate, long rateInterval) {
        return limiterCache.computeIfAbsent(key, k -> {
            RRateLimiter limiter = redissonClient.getRateLimiter(k);
            limiter.trySetRate(org.redisson.api.RateType.OVERALL, rate, rateInterval, org.redisson.api.RateIntervalUnit.SECONDS);
            return limiter;
        });
    }

    /**
     * 根据用户角色获取不同的限流器
     */
    public boolean limitByUserRole(String userId, String apiPath) {
        // 从配置中心或数据库获取限流配置
        RateConfig config = getRateConfigByUserRole(userId);
        RRateLimiter limiter = getDynamicRateLimiter(
                "rate_limit:" + apiPath + ":" + userId,
                config.getRate(),
                config.getRateInterval()
        );
        return limiter.tryAcquire(1);
    }

    private RateConfig getRateConfigByUserRole(String userId) {
        // 这里可以根据用户ID查询用户角色，然后根据角色获取不同的限流配置
        // 实际应用中可能从配置中心或数据库获取
        return new RateConfig(5, 1); // 默认每秒5次请求
    }
}